import 'package:equatable/equatable.dart';
import 'package:mobile_app.home.collections/custom_lexical_item_creation_page/domain/entities/custom_lexical_item_input.dart';
import 'package:mobile_app.home.core/core/domain/helpers/is_custom_lexical_item_use_case_example_valid/helper.dart';

part 'result.dart';

abstract class UpdateCustomLexicalItemUseCaseInputExample {
  CustomLexicalItemUseCaseInputExampleUpdateResult call({
    required String useCaseInputExample,
    required String useCaseInputId,
    required CustomLexicalItemInput customLexicalItemInput,
  });
}

class UpdateCustomLexicalItemUseCaseInputExampleImpl
    implements UpdateCustomLexicalItemUseCaseInputExample {
  const UpdateCustomLexicalItemUseCaseInputExampleImpl({
    required IsCustomLexicalItemUseCaseExampleValid isCustomLexicalItemUseCaseExampleValid,
  }) : _isCustomLexicalItemUseCaseExampleValid = isCustomLexicalItemUseCaseExampleValid;

  final IsCustomLexicalItemUseCaseExampleValid _isCustomLexicalItemUseCaseExampleValid;

  @override
  CustomLexicalItemUseCaseInputExampleUpdateResult call({
    required String useCaseInputExample,
    required String useCaseInputId,
    required CustomLexicalItemInput customLexicalItemInput,
  }) {
    final useCaseInputIndex = customLexicalItemInput.useCaseInputs.indexWhere((useCaseInput) {
      return useCaseInput.id == useCaseInputId;
    });

    final updatedCustomLexicalItemUseCaseInputs =
        customLexicalItemInput.useCaseInputs.rebuild((useCaseInputs) {
      final useCaseInput = useCaseInputs[useCaseInputIndex];

      final exampleValid = _isCustomLexicalItemUseCaseExampleValid(
        customLexicalItemUseCaseExample: useCaseInputExample,
      );

      final updatedUseCaseInput = useCaseInput.copyWith(
        example: () => useCaseInputExample,
        exampleValid: () => exampleValid,
      );

      useCaseInputs[useCaseInputIndex] = updatedUseCaseInput;
    });

    final updatedCustomLexicalItemInput =
        customLexicalItemInput.copyWith(useCaseInputs: () => updatedCustomLexicalItemUseCaseInputs);

    final result = CustomLexicalItemUseCaseInputExampleUpdateResult(
      customLexicalItemInput: updatedCustomLexicalItemInput,
    );

    return result;
  }
}
